<template>
  <div class="table-page">
    <a-form
      label-align="right"
      layout="inline"
      auto-label-width
      :model="commonParam"
      size="small"
      class="form mt-10 mb-20"
    >
      <a-form-item field="sourceChatroomId" label="源头群">
        <a-select
          v-model="commonParam.sourceChatroomId"
          class="w-70n"
          placeholder="选择源头群"
          @change="changeCurrent(1)"
        >
          <a-option value="" label="全部源头群"></a-option>
          <a-option
            v-for="item in sourceList"
            :key="item.sourceChatRoomId"
            :value="item.sourceChatRoomId"
            :label="item.name"
          ></a-option>
        </a-select>
      </a-form-item>
      <a-form-item field="sourceChatroomIds" label="统计日期">
        <ms-date
          v-model:start="commonParam.startAt"
          :disabledDate="
            (current) =>
              dayjs(current).isAfter(dayjs().endOf('date')) ||
              dayjs(current).isBefore(dayjs('2023-09-07').startOf('date'))
          "
          v-model:end="commonParam.endAt"
          :showQuick="true"
          @dateChange="changeCurrent(1)"
        ></ms-date>
      </a-form-item>
      <a-form-item field="inviteCode" hide-label>
        <a-input
          v-model="commonParam.inviteCode"
          placeholder="输入邀请码检索"
          @press-enter="changeCurrent(1)"
        ></a-input>
      </a-form-item>
      <a-form-item>
        <a-space>
          <a-button type="primary" size="small" @click="changeCurrent(1)">
            <template #icon>
              <icon-search />
            </template>
            <template #default>查询</template>
          </a-button>
          <a-button size="small" @click="onResetSearch">
            <template #icon>
              <icon-sync />
            </template>
            <template #default>重置</template>
          </a-button>
        </a-space>
      </a-form-item>
    </a-form>
    <GiTable
      row-key="id"
      ref="tt"
      id="groupOrderStatisticsDetail"
      @sorter-change="onSorterChange"
      v-model:columns="columns"
      :loading="loading"
      :data="tableData"
      :scroll="{ x: '100%', y: '100%', minWidth: 1000 }"
      :pagination="pagination"
      @refresh="getTableData"
    >
      <template #info="{ record }">
        <div class="flex flex-a-c" v-if="record.wxInfo">
          <a-avatar>
            <img alt="avatar" :src="record.wxInfo.vcHeadImgUrl" />
          </a-avatar>
          <div class="ml-10">
            <div>{{ record.wxInfo.vcNickName }}</div>
            <div>{{ record.wxInfo.vcRobotWxId }}</div>
          </div>
        </div>
        <span v-else>--</span>
      </template>
      <template #platform="{ record }">
        <template v-if="record.name">
          <span>{{ record.name }}</span>
        </template>
        <template v-else>
          <a-button type="text" size="small" @click="onMore(record.id, !record.isOpen)">
            {{ record.isOpen ? '收起' : '展开查看' }}
          </a-button>
        </template>
      </template>
    </GiTable>
  </div>
</template>

<script setup>
import dayjs from 'dayjs'
import { useSource } from '@/hooks/app'
import { sourceChatRoomUserWechatRankData } from '@/apis'
import { deleteEmpty } from '@/utils/common'
import { useTabsStore } from '@/store'
import { usePagination } from '@/hooks'

defineOptions({ name: 'groupOrderStatisticsDetail' })
const route = useRoute()
const tableData = ref([])
const loading = ref(false)
const tabsStore = useTabsStore()
const key = route.fullPath
const tt = ref()
const { pagination, setTotal } = usePagination(() => getTableData(), { defaultPageSize: 20 })

// 公共参数
const commonParam = ref({
  sourceChatroomId: undefined,
  page: 1,
  startAt: undefined,
  endAt: undefined,
  inviteCode: undefined
})

const formO = ref()

const columns = ref([
  {
    title: '设备信息',
    width: 200,
    slotName: 'info'
  },
  {
    title: '邀请码',
    width: 100,
    dataIndex: 'inviteCode',
    render: ({ record }) => {
      return record.inviteCode || '--'
    }
  },
  {
    title: '各平台数据',
    width: 180,
    align: 'center',
    slotName: 'platform'
  },
  {
    title: 'GMV(元)',
    width: 130,
    align: 'center',
    dataIndex: 'totalGmv',
    sortable: {
      sortDirections: ['ascend', 'descend']
    }
  },
  {
    title: '有效GMV(元)',
    width: 130,
    align: 'center',
    dataIndex: 'validGmv',
    sortable: {
      sortDirections: ['ascend', 'descend']
    }
  },
  {
    title: '订单量(单)',
    width: 130,
    align: 'center',
    dataIndex: 'totalOrderCount',
    sortable: {
      sortDirections: ['ascend', 'descend']
    }
  },
  {
    title: '有效订单量(单)',
    width: 130,
    align: 'center',
    dataIndex: 'validOrderCount',
    sortable: {
      sortDirections: ['ascend', 'descend']
    }
  },
  {
    title: '失效订单量(单)',
    width: 130,
    align: 'center',
    dataIndex: 'invalidOrderCount',
    sortable: {
      sortDirections: ['ascend', 'descend']
    }
  },
  {
    title: '预估佣金(元)',
    width: 130,
    align: 'center',
    dataIndex: 'totalCommission',
    sortable: {
      sortDirections: ['ascend', 'descend']
    }
  },
  {
    title: '商品数(个)',
    width: 130,
    align: 'center',
    dataIndex: 'totalGoodsCount',
    sortable: {
      sortDirections: ['ascend', 'descend']
    }
  },
  {
    title: '爆品数量(个)',
    width: 130,
    align: 'center',
    dataIndex: 'hotSaleGoodsCount',
    sortable: {
      sortDirections: ['ascend', 'descend']
    }
  }
])

// 获取源头群
const { sourceList, getSourceList } = useSource()
getSourceList()

// 初始化表单值
onMounted(() => {
  if (sessionStorage.getItem(key) || history.state.item) {
    if (history.state.item) {
      sessionStorage.setItem(key, history.state.item)
    } else {
      history.state.item = sessionStorage.getItem(key)
    }
    formO.value = JSON.parse(history.state.item)
  }
  Object.assign(commonParam.value, formO.value)
  tabsStore.changeTagTitle('源头挂设备详情')
  getTableData()
})

onUnmounted(() => {
  sessionStorage.removeItem(key)
})

// 获取头部信息
const getTableData = async () => {
  try {
    loading.value = true
    commonParam.value.page = pagination.current
    const res = await sourceChatRoomUserWechatRankData(deleteEmpty({ ...commonParam.value }))
    tableData.value = res.data.map((item, index) => {
      return {
        ...item,
        id: index + 600,
        children: item.platformInfo,
        isOpen: false
      }
    })
    setTotal(10000)
  } finally {
    loading.value = false
  }
}

// 表格页码改变
const changeCurrent = (e) => {
  pagination.current = commonParam.value.page = e
  getTableData()
}

//升降序发生改变
const onSorterChange = (dataIndex, direction) => {
  commonParam.value.orderBy = direction ? (direction === 'ascend' ? 'asc' : 'desc') : undefined
  commonParam.value.sort = commonParam.value.orderBy ? dataIndex : undefined
  changeCurrent(1)
}

//点击展开更多
const onMore = (id, type) => {
  if (type) {
    tableData.value.forEach((item) => {
      item.isOpen = false
    })
    tt.value.tableRef.expandAll(false)
  }
  tt.value.tableRef.expand(id, type)
  const index = tableData.value.findIndex((item) => {
    return item.id === id
  })
  tableData.value[index].isOpen = type
}

// 重置筛选查询
const onResetSearch = () => {
  Object.assign(commonParam.value, formO.value)
  commonParam.value.inviteCode = undefined
  changeCurrent(1)
}
</script>

<style lang="scss" scoped>
.table-page {
  height: 100%;
  overflow: hidden;
  margin: $margin;
  background: var(--color-bg-1);
  padding: $padding;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  .form {
    :deep(.arco-form-item) {
      margin-bottom: 10px;
    }
  }
  :deep(.arco-table-cell-inline-icon) {
    display: none;
  }
}
</style>
